package http_response

import (
	"context"
	"errors"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/gin-gonic/gin"
)

// Response 返回参数
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
	Success bool        `json:"success"`
}

// NewErrResponse 失败返回
func NewErrResponse(code int, err error, data interface{}) *Response {
	return &Response{
		Code:    code,
		Message: err.Error(),
		Data:    data,
		Success: false,
	}
}

// NewSuccessResponse 成功返回
func NewSuccessResponse(code int, message string, data interface{}) *Response {
	return &Response{
		Code:    code,
		Message: message,
		Data:    data,
		Success: true,
	}
}

/*
 * @Description: 字节赫兹(Hertz)框架返回参数
 * @param
 * @Auther xvwen
 * @Time: 2024/2/7 17:14
 */

func HertzErrResp(ctx context.Context, c *app.RequestContext, err error) {
	errResp := Response{}
	errResp.Code = 500
	errResp.Message = err.Error()
	errResp.Data = err
	errResp.Success = false
	c.JSON(500, errResp)
}
func HertzSuccessResp(ctx context.Context, c *app.RequestContext, message string, data interface{}) {
	successResp := Response{}
	successResp.Code = 200
	successResp.Message = message
	successResp.Data = data
	successResp.Success = true
	c.JSON(200, successResp)
}
func HertzNewResponse[T Response](ctx context.Context, c *app.RequestContext, x T) {
	resp := Response(x)
	var result *Response
	if resp.Success {
		result = NewSuccessResponse(resp.Code, resp.Message, resp.Data)
	}
	result = NewErrResponse(resp.Code, errors.New(resp.Message), resp.Data)
	c.JSON(resp.Code, result)
	return
}

/*
 * @Description: Gin框架返回参数
 * @param
 * @Auther xvwen
 * @Time: 2024/2/7 17:14
 */

func GinErrResp(ctx context.Context, c *gin.Context, err error) {
	errResp := Response{}
	errResp.Code = 500
	errResp.Message = err.Error()
	errResp.Data = err
	errResp.Success = false
	c.JSON(500, errResp)
}

func GinSuccessResp(ctx context.Context, c *gin.Context, message string, data interface{}) {
	successResp := Response{}
	successResp.Code = 200
	successResp.Message = message
	successResp.Data = data
	successResp.Success = true
	c.JSON(200, successResp)
}

func GinNewResponse[T struct{} | map[string]any](ctx context.Context, c *gin.Context, code int, data T) {
	resp := Response{}
	var result *Response
	if resp.Success {
		result = NewSuccessResponse(resp.Code, resp.Message, resp.Data)
	}
	result = NewErrResponse(resp.Code, errors.New(resp.Message), resp.Data)
	c.JSON(resp.Code, result)
	return
}
